package control.config;

import base.standard.constant.ThreadLocalParams;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.Date;

/**
 * Mybatis plus config
 *
 * @description: MP添加分页插件配置 + 自动填充时间配置
 * @author: cyj
 * @date 2020 -10-15 17:22:31
 */
@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig implements MetaObjectHandler {

    /**
     * Pagination interceptor pagination interceptor
     *
     * @return the pagination interceptor
     * @description:
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        // 设置最大单页限制数量，默认 500 条，-1 不受限制
        paginationInterceptor.setLimit(500);
        // 开启 count 的 join 优化,只针对部分 left join
        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
        return paginationInterceptor;
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        // 设置自动填入，在MP做插入更新数据的时候，自动填充这些字段
        this.setFieldValByName("createDate", new Date(), metaObject);
        this.setFieldValByName("createBy", ThreadLocalParams.getLoginId(), metaObject);
        this.setFieldValByName("updateDate", new Date(), metaObject);
        this.setFieldValByName("updateBy", ThreadLocalParams.getLoginId(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 设置自动填入，在MP做插入更新数据的时候，自动填充这些字段
        this.setFieldValByName("updateDate", new Date(), metaObject);
        this.setFieldValByName("updateBy", ThreadLocalParams.getLoginId(), metaObject);
    }
}
